#!/usr/bin/php
<?php
$_SERVER["DOCUMENT_ROOT"] = "/home/bitrix/www";
$DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"];
define("NO_KEEP_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
set_time_limit(0);
define("LANG", "ru");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
?>

<?
$f = fopen($_SERVER["DOCUMENT_ROOT"]."/agents/log_posvu.txt", "w+");
fwrite($f, "**********************************\r\n*** запуск ".date("d.m.Y H:i:s")." ***\r\n**********************************\r\n");

if(!CModule::IncludeModule("iblock"))
{
    ShowError("Модуль Информационных блоков не установлен");
    return;
}
?>

<? 
$IBLOCK_ID = "41";
$IBLOCK_LOGS_ID = "42";
$GROUP_ADMINS = "12";
$GROUP_SUPPORT = "14";
$BITRIX_ADMIN_ID = "804";
$MAIL_TEMPL_PREFIX = "REQUESTS_POSVU";

// выбираем свойства инфоблока для определения типа комментария
$types = array();
$prs = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$IBLOCK_LOGS_ID, "CODE"=>"TYPE"));
while($field = $prs->GetNext())
{
    $types[$field["VALUE"]] = $field["ID"];
}


$requests = CIBlockElement::GetList(
        array("ID"=>"ASC"),
        array("IBLOCK_ID"=>$IBLOCK_ID, "ACTIVE"=>"Y", "PROPERTY_DATE_CLOSE"=>false),
        false,
        false,
        Array("ID", "NAME", "IBLOCK_ID", "CREATED_BY", "DATE_CREATE", "PROPERTY_STATUS", "PROPERTY_CATEGORY", "PROPERTY_RESPONSIBLE_USER", "PROPERTY_CRITICALITY", "PROPERTY_DIFFICULTY", "PROPERTY_RATE", "PROPERTY_DATE_CLOSE")
);

while($request = $requests->GetNext())
{
    fwrite($f, "обрабатываем заявку ID=".$request["ID"]."\r\n");
    
    $logs = CIBlockElement::GetList(
        array("ID"=>"ASC"),
        array("IBLOCK_ID"=>$IBLOCK_LOGS_ID, "ACTIVE"=>"Y", "PROPERTY_REQUEST"=>$request["ID"]),
        false,
        false,
        array("ID", "CREATED_BY", "DATE_CREATE", "PREVIEW_TEXT", "PROPERTY_TYPE")
    );
    while($log = $logs->GetNext())
    {
        $request["LOG"][] = $log;
    }
    
    //$status = GetIBlockElement($request["PROPERTY_STATUS_VALUE"]);
    $items = CIBlockElement::GetList(
        array("ID"=>"ASC"),
        array("ID"=>$request["PROPERTY_STATUS_VALUE"], "ACTIVE"=>"Y"),
        false,
        false,
        array("ID", "NAME")
    );
    if ($item = $items->GetNext())
        $status["NAME"] = $item["NAME"];
    else
        $status["NAME"] = "";
       
    // проверка на завершенную задачу (если последнее сообщение оставлено техподдержкой - закрывать, иначе сообщение автору)
    if ($status["NAME"]=="Успешно решено")
    {
        fwrite($f, "статус заявки - ".$status["NAME"]."\r\n");
    
        // перебираем лог заявки и ищем ключевые точки
        $timeLastAnswerSupport = "";
        $timeLastAnswerOwner = $request["DATE_CREATE"];
        $timeSetCompleted = "";
        $timeSendReminder = "";
        foreach($request["LOG"] as $log)
        {
            if ($log["PROPERTY_TYPE_VALUE"]=="Системная")
            {
                if (strpos($log["PREVIEW_TEXT"], "Успешно решено")!==false)
                        $timeSetCompleted = $log["DATE_CREATE"];
                
                if (strpos($log["PREVIEW_TEXT"], "Отправлено напоминание автору заявки")!==false)
                        $timeSendReminder = $log["DATE_CREATE"];
            }
            else
            if (in_array($GROUP_ADMINS, CUser::GetUserGroup($log["CREATED_BY"])) || in_array($GROUP_SUPPORT, CUser::GetUserGroup($log["CREATED_BY"])))
                $timeLastAnswerSupport = $log["DATE_CREATE"];
            else
                $timeLastAnswerOwner = $log["DATE_CREATE"];                                                
        }
        
        if (strlen($timeLastAnswerSupport)==0)
            $timeLastAnswerSupport = $timeSetCompleted;

        $dtCreated = date_create($request["DATE_CREATE"]);
        $dtLastAnswerSupport = date_create($timeLastAnswerSupport);
        $dtLastAnswerOwner = date_create($timeLastAnswerOwner);
        $dtSetCompleted = date_create($timeSetCompleted);
        $dtSendReminder = date_create($timeSendReminder);
        $dtCurrent = date_create("now");
        
        $action = 0;
        if ($dtSetCompleted>$dtCreated)
        {
            fwrite($f, "Current = ".date("now")."\r\n");
            fwrite($f, "Created = ".$request["DATE_CREATE"]."\r\n");
            fwrite($f, "AnswerSupport = ".$timeLastAnswerSupport."\r\n");
            fwrite($f, "AnswerOwner = ".$timeLastAnswerOwner."\r\n");
            fwrite($f, "SetCompleted = ".$timeSetCompleted."\r\n");
            fwrite($f, "SendReminder = ".$timeSendReminder."\r\n");
            
            fwrite($f, "Дата установки успешно решено больше даты создания заявки\r\n");
            
            if ($dtLastAnswerSupport>$dtLastAnswerOwner)
                fwrite($f, "Дата последнего ответа сотрудника ТП больше даты ответа автора\r\n");
            
            fwrite($f, "Разница между текущей датой и датой последнего ответа сотрудника ТП - ".date_diff($dtLastAnswerSupport,$dtCurrent,true)->format('%r%a')."\r\n");                       
            
            fwrite($f, "Разница между текущей датой и датой последнего напоминания о закрытии - ".date_diff($dtSendReminder,$dtCurrent,true)->format('%r%a')."\r\n");
            
            if (($dtLastAnswerSupport>$dtLastAnswerOwner) && (date_diff($dtLastAnswerSupport,$dtCurrent,true)->format('%r%a')>3) && ((strlen($timeSendReminder)==0)||(date_diff($dtSendReminder,$dtCurrent,true)->format('%r%a')>7)))
                $action = 1;                
            else
            if (($dtLastAnswerSupport>$dtLastAnswerOwner) && (date_diff($dtSendReminder,$dtCurrent,true)->format('%r%a')>4))
                $action = 2;
        }
        
        fwrite($f, "результат обработки времен - ".$action."\r\n");
        
        if ($action==1)
        {
            // системная запись в лог о автоматическом закрытии заявки
            $el = new CIBlockElement;
            $PROP = array();
            $PROP["REQUEST"] = $request["ID"];
            $PROP["TYPE"] = $types["Системная"];
            $arLoadArray = Array(
                "MODIFIED_BY"       => $BITRIX_ADMIN_ID,
                "CREATED_BY"        => $BITRIX_ADMIN_ID,
                "PROPERTY_VALUES"   => $PROP,
                "IBLOCK_ID"         => $IBLOCK_LOGS_ID,
                "NAME"              => "Системная запись к заявке #".$request["ID"],
                "ACTIVE"            => "Y",
                "PREVIEW_TEXT"      => "Отправлено напоминание автору заявки",
                "PREVIEW_TEXT_TYPE" => "html"
            );
            if (!$el->Add($arLoadArray))
                echo "Error: ".$el->LAST_ERROR;               
            
            // отсылаем напоминание автору
            $rsUser = CUser::GetByID($request["CREATED_BY"]);    
            $pitem = $rsUser->Fetch();
            $MESS["EMAIL_TO"] = $pitem["EMAIL"];
            $MESS["OWNER_NAME"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
            if ($request["PROPERTY_RESPONSIBLE_USER_VALUE"]>0)
            {
                $rsUser = CUser::GetByID($request["PROPERTY_RESPONSIBLE_USER_VALUE"]);    
                $pitem = $rsUser->Fetch();
                $MESS["RESPONSIBLE_USER"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
            }
            else
                $MESS["RESPONSIBLE_USER"] = "";
            
            if ($dtLastAnswerSupport>$dtLastAnswerOwner)
                $MESS["TIMESTAMP"] = $timeLastAnswerSupport;
            else
                $MESS["TIMESTAMP"] = $timeLastAnswerOwner;
            
            if ($request["PROPERTY_CATEGORY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_CATEGORY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $category["NAME"] = $item["NAME"];
                else
                    $category["NAME"] = "";
            }
            else
                $category["NAME"] = "";
            
            if ($request["PROPERTY_CRITICALITY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_CRITICALITY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $crit["NAME"] = $item["NAME"];
                else
                    $crit["NAME"] = "";                
            }
            else
                $crit["NAME"] = "";

            if ($request["PROPERTY_DIFFICULTY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_DIFFICULTY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $diffic["NAME"] = $item["NAME"];
                else
                    $diffic["NAME"] = "";                                
            }
            else
                $diffic["NAME"] = "";

            if ($request["PROPERTY_RATE_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_RATE_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $rate["NAME"] = $item["NAME"];
                else
                    $rate["NAME"] = "";                 
            }
            else
                $rate["NAME"] = "";
            
            
            $arEventFields = array(
                "ID"                  => $request["ID"],
                "EMAIL_TO"            => $MESS["EMAIL_TO"],
                "TIMESTAMP"           => $MESS["TIMESTAMP"],
                "TITLE"               => $request["NAME"],
                "OWNER_NAME"          => $MESS["OWNER_NAME"],
                "CATEGORY"            => $category["NAME"],
                "STATUS"              => $status["NAME"],
                "CRITICALITY"         => $crit["NAME"],
                "DIFFICULTY"          => $diffic["NAME"],
                "DATE_CREATE"         => $request["DATE_CREATE"],
                "RESPONSIBLE_NAME"    => $MESS["RESPONSIBLE_USER"],
                "RATE"                => $rate["NAME"],
                "MESSAGE"             => "Заявка будет автоматически закрыта через 4 дня при отсутствии вашей реакции."
            );
            CEvent::Send($MAIL_TEMPL_PREFIX."_AUTOCLOSE", "s1", $arEventFields, "N");            
        }
        else
        if ($action==2) // подумать над условием
        {
            // закрываем заявку
            CIBlockElement::SetPropertyValues($request["ID"], $request["IBLOCK_ID"], $BITRIX_ADMIN_ID, "USER_CLOSE");
            CIBlockElement::SetPropertyValues($request["ID"], $request["IBLOCK_ID"], date("d.m.Y h:i:s"), "DATE_CLOSE");
            
            // системная запись в лог о автоматическом закрытии заявки
            $el = new CIBlockElement;
            $PROP = array();
            $PROP["REQUEST"] = $request["ID"];
            $PROP["TYPE"] = $types["Системная"];
            $arLoadArray = Array(
                "MODIFIED_BY"       => $BITRIX_ADMIN_ID,
                "CREATED_BY"        => $BITRIX_ADMIN_ID,
                "PROPERTY_VALUES"   => $PROP,
                "IBLOCK_ID"         => $IBLOCK_LOGS_ID,
                "NAME"              => "Системная запись к заявке #".$request["ID"],
                "ACTIVE"            => "Y",
                "PREVIEW_TEXT"      => "Закрыто автоматически",
                "PREVIEW_TEXT_TYPE" => "html"
            );
            if (!$el->Add($arLoadArray))
                echo "Error: ".$el->LAST_ERROR;               
            
            // отправка письма автору и исполнителю
            $rsUser = CUser::GetByID($request["CREATED_BY"]);    
            $pitem = $rsUser->Fetch();
            $MESS["EMAIL_TO"] = $pitem["EMAIL"];
            $MESS["OWNER_NAME"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
            if ($request["PROPERTY_RESPONSIBLE_USER_VALUE"]>0)
            {
                $rsUser = CUser::GetByID($request["PROPERTY_RESPONSIBLE_USER_VALUE"]);    
                $pitem = $rsUser->Fetch();
                $MESS["EMAIL_TO"] .= ",".$pitem["EMAIL"];
                $MESS["RESPONSIBLE_USER"] = $pitem["NAME"]." ".$pitem["LAST_NAME"];
            }
            else
                $MESS["RESPONSIBLE_USER"] = "";
            
            if ($dtLastAnswerSupport>$dtLastAnswerOwner)
                $MESS["TIMESTAMP"] = $timeLastAnswerSupport;
            else
                $MESS["TIMESTAMP"] = $timeLastAnswerOwner;
            
            if ($request["PROPERTY_CATEGORY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_CATEGORY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $category["NAME"] = $item["NAME"];
                else
                    $category["NAME"] = "";
            }
            else
                $category["NAME"] = "";
            
            if ($request["PROPERTY_CRITICALITY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_CRITICALITY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $crit["NAME"] = $item["NAME"];
                else
                    $crit["NAME"] = "";                
            }
            else
                $crit["NAME"] = "";

            if ($request["PROPERTY_DIFFICULTY_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_DIFFICULTY_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $diffic["NAME"] = $item["NAME"];
                else
                    $diffic["NAME"] = "";                                
            }
            else
                $diffic["NAME"] = "";

            if ($request["PROPERTY_RATE_VALUE"]>0)
            {
                $items = CIBlockElement::GetList(
                    array("ID"=>"ASC"),
                    array("ID"=>$request["PROPERTY_RATE_VALUE"], "ACTIVE"=>"Y"),
                    false,
                    false,
                    array("ID", "NAME")
                );
                if ($item = $items->GetNext())
                    $rate["NAME"] = $item["NAME"];
                else
                    $rate["NAME"] = "";                 
            }
            else
                $rate["NAME"] = "";
            
            
            $arEventFields = array(
                "ID"                  => $request["ID"],
                "EMAIL_TO"            => $MESS["EMAIL_TO"],
                "TIMESTAMP"           => $MESS["TIMESTAMP"],
                "TITLE"               => $request["NAME"],
                "OWNER_NAME"          => $MESS["OWNER_NAME"],
                "CATEGORY"            => $category["NAME"],
                "STATUS"              => $status["NAME"],
                "CRITICALITY"         => $crit["NAME"],
                "DIFFICULTY"          => $diffic["NAME"],
                "DATE_CREATE"         => $request["DATE_CREATE"],
                "RESPONSIBLE_NAME"    => $MESS["RESPONSIBLE_USER"],
                "RATE"                => $rate["NAME"],
                "MESSAGE"             => "Заявка автоматически закрыта по истечении 7 дней после выставления статуса \"Успешно решено\" и отсутствия реакции автора заявки."
            );
            CEvent::Send($MAIL_TEMPL_PREFIX."_AUTOCLOSE", "s1", $arEventFields, "N");                   
        }
    }
    
    // проверка на отсутствие ответственного исполнителя
    
    
    
    
    fwrite($f, "----\r\n");
}

fclose($f);
?>

